<template>
	<div class="alarmConfiguration zy-content">
		<!-- 搜索 -->
		<search :columns="searchData" @getSearch="getSearch(arguments)" key="search"></search>
		<div class="alarmConfiguration">
			<div class="list-layout mt16">
				<!-- 批量删除 批量导出  批量导入 下载模板 新增-->
				<div class="btns clear">
					<span class="title">{{ $t('common.listInformation') }}</span>
					<Button @click="addWareHouse()">{{ $t('common.New') }}</Button>
				</div>
				<!-- 表格 -->
				<div class="tableContent">
					<Table
						class="resizable-table"
						border
						@on-column-width-resize="onColumnWidthResize"
						:columns="columnsList"
						ellipsis
						ref="selection"
						stripe
						:data="dataArr"
					>
						<template slot-scope="{ row }" slot="action">
							<span class="operationBtn" v-if="row.receiptStatus == 1" @click="clickRow(row, 'comp')">完成</span>
							<span class="operationBtn" v-if="row.receiptStatus == 1" @click="clickRow(row, 'rej')"> 驳回 </span>
							<span class="operationBtn" v-if="row.receiptStatus == 1" @click="clickRow(row, 'edit')">{{ $t('common.Edit') }}</span>
							<span class="operationBtn" v-if="row.receiptStatus == 1" @click="clickRow(row, 'del')"
								><i class="iconfont zy-common-shanchu"></i>{{ $t('common.Delete') }}</span
							>
						</template>
					</Table>
				</div>
				<!-- 分页 -->
				<div class="pageWrap mt16">
					<pageLeftTitle :total="total" :selected="delIds.length" />
					<Page
						:total="total"
						:page-size="pageSize"
						:page-size-opts="pageSizeOption"
						:current="pageNum"
						@on-change="changePageNum"
						@on-page-size-change="changePageSize"
						show-sizer
						show-total
					/>
				</div>
			</div>
			<!-- 新增 -->
			<Modal :mask-closable="false" v-model="addWareDialog" :title="title" class="modal-content-layout" width="40%">
				<Form ref="form" class="formList" :model="formItem" label-position="top" :rules="ruleValidate">
					<Row :gutter="20">
						<Col span="12">
							<FormItem label="工装编号" prop="moldCode">
								<Select
									v-model="formItem.moldCode"
									filterable
									clearable
									:remote-method="getMoldInfo"
									@on-change="getMoldInfoChange"
									:placeholder="`${$t('common.selectInfo')}`"
								>
									<Option v-for="(item, index) of moldInfoList" :value="item.moldCode" :key="index" :label="item.moldCode"> </Option>
								</Select>
							</FormItem>
						</Col>
						<Col span="12">
							<FormItem label="工装名称" prop="moldName">
								<Input type="text" v-model="formItem.moldName" disabled :placeholder="`${$t('common.inputInfo')}`"></Input>
							</FormItem>
						</Col>
					</Row>
					<Row :gutter="20">
						<Col span="12">
							<FormItem label="功能位置" prop="functionalLocation">
								<Cascader
									clearable
									ref="cascader"
									:data="orgList"
									v-model="formItem.functionalLocation"
									@on-change="changeLocation"
									placeholder="请选择"
								>
								</Cascader>
							</FormItem>
						</Col>
						<Col span="12">
							<FormItem label="库区" prop="reservoirArea">
								<!-- <Input type="text" v-model="formItem.reservoirArea" :placeholder="`${$t('common.inputInfo')}`"></Input> -->
								<Select v-model="formItem.reservoirArea" filterable clearable @on-change="kuquChange" :placeholder="`${$t('common.selectInfo')}`">
									<Option v-for="(item, index) of kuquList" :value="item.mreservoir" :key="index" :label="item.mreservoir"> </Option>
								</Select>
							</FormItem>
						</Col>
					</Row>
					<Row :gutter="20">
						<Col span="12">
							<FormItem label="库位" prop="warehouseLocation">
								<Select v-model="formItem.warehouseLocation" filterable clearable :placeholder="`${$t('common.selectInfo')}`">
									<Option v-for="(item, index) of kuweiList" :value="item.mwarehouse" :key="index" :label="item.mwarehouse"> </Option>
								</Select>
							</FormItem>
						</Col>
						<Col span="12">
							<FormItem label="入库类型" prop="receiptType">
								<Select v-model="formItem.receiptType" clearable :placeholder="`${$t('common.selectInfo')}`">
									<Option v-for="item of receiptTypeList" :value="item.value" :key="item.value">{{ item.value }} </Option>
								</Select>
							</FormItem>
						</Col>
					</Row>
					<Row :gutter="20">
						<Col span="24">
							<FormItem label="入库事由" prop="reasonStorage">
								<Input type="text" maxlength="200" v-model="formItem.reasonStorage" :placeholder="`${$t('common.inputInfo')}`"></Input>
							</FormItem>
						</Col>
						<Col span="24">
							<FormItem label="备注" prop="remarks">
								<Input type="text" maxlength="200" v-model="formItem.remarks" :placeholder="`${$t('common.inputInfo')}`"></Input>
							</FormItem>
						</Col>
					</Row>
				</Form>
				<div slot="footer">
					<Button type="default" @click="addWareDialog = false">{{ $t('common.Cancle') }}</Button>
					<Button type="primary" :loading="loading" @click="addOk('form')">{{ $t('maintenance.Confirmed') }}</Button>
				</div>
			</Modal>
			<commonModal ref="commonModal"></commonModal>
			<inputModal ref="inputModal"></inputModal>
		</div>
	</div>
</template>
<script>
import { searchApi, addApi, deleteApi, getMoldInfoList, updateMoldWarehousing } from '@/api/moldManagement/moldInApply.js';
import search from '@/components/curd/searchList.vue';
import toggleTableOperation from '@/mixins/toggleTableOperation';
import { findOrgByToken, getDictData } from '@/api/index.js';
import recursion from '@/util/recursion';
import inputModal from '@/components/modalTypes/inputModal.vue';
import commonModal from '@/components/modalTypes/commonModal.vue';

export default {
	name: 'storeHouse', //仓库配置
	components: { search, inputModal, commonModal },
	mixins: [toggleTableOperation],
	data() {
		return {
			searchData: [
				{
					title: '功能位置',
					key: 'functionalLocation',
					type: 'cascader',
					dicUrl: '/basic/organization/findListByToken?level=0',
					params: {
						label: 'name',
						value: 'code',
						children: 'children',
					},
				},
				{
					title: '入库类型',
					key: 'receiptType',
					type: 'select',
					dicUrl: '/dms/faultCategory/dictList?name=入库类型',
					params: {
						label: 'value',
						value: 'value',
					},
				},
				{
					title: '入库状态',
					key: 'receiptStatus',
					type: 'select',
					dicData: [
						{
							label:'完成',
							value: 0,
						},
						{
							label:'待入库',
							value: 1,
						},
						{
							label:'驳回',
							value: 2,
						},
					],
				},
        {
					title: '工装编号',
					key: 'moldCode',
				},
        {
					title: '工装名称',
					key: 'moldName',
				},
        {
					title: '库区',
					key: 'reservoirArea',
				},
        {
					title: '库位',
					key: 'warehouseLocation',
				},
        {
					title: '申请时间',
					key: 'time',
          type:'datetimerange',
          format:'yyyy-MM-dd HH:mm:ss',
          span:8
				},
			],
			receiptTypeList: [],
			receiptStatusList: [
				{ label: '完成', value: '0' },
				{ label: '待入库', value: '1' },
				{ label: '驳回', value: '2' },
			],
			columns: [
				{
					title: '入库类型',
					key: 'receiptType',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '入库状态',
					key: 'receiptStatus',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
					render: (h, params) => {
						return h(
							'div',
							this.receiptStatusList.find((item) => {
								return item.value == params.row.receiptStatus;
							}).label
						);
					},
				},
				{
					title: '工装编号',
					key: 'moldCode',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '功能位置',
					key: 'functionalLocationName',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '工装名称',
					key: 'moldName',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '入库事由',
					key: 'reasonStorage',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '申请时间',
					key: 'applicationTime',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '申请人',
					key: 'applicant',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '操作',
					minWidth: 280,
					slot: 'action',
					align: 'center',
				},
			],
			columns1: [
				{
					title: '工装名称',
					key: 'moldName',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '资产编号',
					key: 'moldCode',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
				{
					title: '工装编号',
					key: 'moldName',
					minWidth: 100,
					align: 'center',
					resizable: true,
					tooltip: true,
				},
			],
			locationCode: [],
			checkBtnPermission: {},
			ruleValidate: {
				moldCode: [{ required: true, message: this.$t('common.selectInfo') }],
				functionalLocation: [{ required: true, message: this.$t('common.inputInfo') }],
				warehouseLocation: [{ required: true, message: this.$t('common.inputInfo') }],
				reservoirArea: [{ required: true, message: this.$t('common.inputInfo') }],
				receiptType: [{ required: true, message: this.$t('common.inputInfo') }],
			},
			moldInfoList: [],
			addWareDialog: false,
			infoDialogView: false,

			formItem: {},
			allCheck: false,
			loading: false,
			create: false,
			searchParams: {},
			searchParams1: {},
			title: '',
			orgList: [],
			pageNum: 1,
			pageSize: 10,
			total: 0,
			dataArr: [],
			compDialog: false,
			rejDialog: false,

			pageSizeOption: [10, 20, 30, 40],
			delIds: [],
			selection: [],
			kuweiList: [],
			kuquList: [],
		};
	},
	mounted() {
		// 获取入库类型
		this.getDictList();
		this.getTableColumnsWidth(this.columns);
		this.searchList();
		this.getOrgList();
		let itemList = JSON.parse(window.localStorage.getItem('USER_URI'));
		for (let item of itemList) {
			if (item.code == 'moldLedgerAddBtn') {
				this.checkBtnPermission.moldLedgerAddBtn = true;
			}
		}
	},

	methods: {
		getDictList() {
			getDictData('入库类型').then((res) => {
				this.receiptTypeList = res.data;
			});
		},
		async changeLocation(val) {
			this.locationCode = [];
			this.formItem.reservoirArea='';
			if (val && val.length) {
				this.locationCode = [val.at(-1)];
			} else return;
			const res = await this.axios({
				method: 'post',
				url: '/dms/moldStoragelocation/getFunctionalLocationList',
				data: {
					// pageNum: 1,
					// pageSize: 9999,
					mlocationCode: this.locationCode,
				},
			})
			this.kuquList = res.data;
		},
		async kuquChange(val) {
			const res=await this.axios({
				method: 'post',
				url: '/dms/moldStoragelocation/getFunctionalLocationList',
				data: {
					// pageNum: 1,
					// pageSize: 9999,
					mreservoir: val,
					mlocationCode: this.locationCode,
				},
			})
			this.kuweiList = res.data;
		},
		
		async getMoldInfo(query) {
			const res = await getMoldInfoList({ moldCode: query });
			if (res.code == 200) {
				this.moldInfoList = res.data.records;
			} else {
				this.$Message.warning({
					content: res.msg,
					duration: 6,
					closable: true,
				});
			}
		},
		getSearch(params) {
			this.searchParams = JSON.parse(JSON.stringify(params[0]));
			const { functionalLocation,time } = this.searchParams;
			if (functionalLocation && functionalLocation.length) {
				this.searchParams.functionalLocation = [functionalLocation.at(-1)];
			} else delete this.searchParams.functionalLocation;
      if(time && time.length>0){
        this.searchParams.applicationStartTime=time[0];
        this.searchParams.applicationEndTime=time[1];
      }
      delete this.searchParams.time;
			this.pageNum = 1;
			this.searchList();
		},
		change(val) {
			this.formItem.mlocationCode = val;
			this.formItem.mlocation = this.$refs['cascader'].displayRender;
		},
		async getMoldInfoChange(params) {
			if (!params) {
				this.formItem.moldName = '';
				return;
			}
			const data = this.moldInfoList.find((item) => item.moldCode == params) || {};
			this.formItem.moldName = data.moldName;
			if (data.functionalLocationName) {
				this.$set(this.formItem, 'functionalLocation', data.functionalLocationName);

				await this.changeLocation(data.functionalLocationName)
				this.$set(this.formItem, 'reservoirArea', data.reservoirArea);

				await this.kuquChange(data.reservoirArea);
				this.$set(this.formItem, 'warehouseLocation', data.warehouseLocation);
			}
			
		},
		async clickRow(row, status) {
			let personnel = window.localStorage.getItem('ziyunFactoryPortalName');
			this.row = row;
			if (status == 'edit') {
				this.title = '编辑';
				this.$refs.form.resetFields();
				await this.getMoldInfo(this.row.moldCode);

				await this.changeLocation(this.row.functionalLocation)

				await this.kuquChange(this.row.reservoirArea);

				this.formItem = JSON.parse(JSON.stringify(this.row));
				this.addWareDialog = true;
			} else if (status == 'rej') {
				this.$refs.inputModal.showModal({
					title: '驳回',
					submit: (form) => {
						this.axios({
							method: 'post',
							url: '/dms/moldWarehousing/approval',
							data: {
								...row,
								reasonRejection: form.value,
								receiptStatus: '2',
								personnel,
							},
						}).then((res) => {
							if (res.code === 200) {
								this.$Message.success(res.msg);
								this.searchList();
							} else {
								this.$Message.warning({
									content: res.msg,
									duration: 6,
									closable: true,
								});
							}
						});
					},
				});
			} else if (status == 'comp') {
				this.$refs.commonModal.showModal({
					title: '完成提醒',
					type: 'sure',
					desc: '确认入库完成',
					submit: () => {
						this.axios({
							method: 'post',
							url: '/dms/moldWarehousing/approval',
							data: { ...row, receiptStatus: '0', personnel },
						}).then((res) => {
							if (res.code === 200) {
								this.$Message.success(res.msg);
								this.searchList();
							} else {
								this.$Message.warning({
									content: res.msg,
									duration: 6,
									closable: true,
								});
							}
						});
					},
				});
			} else if (status == 'del') {
				this.$refs.commonModal.showModal({
					type: 'delete',
					title: '删除提醒',
					desc: '确认是否删除',
					submit: () => {
						deleteApi({ id: row.id }).then((res) => {
							if (res.code === 200) {
								this.$Message.success(res.msg);
								this.searchList();
							} else {
								this.$Message.warning({
									content: res.msg,
									duration: 6,
									closable: true,
								});
							}
						});
					},
				});
			}
		},
		//增加或编辑
		addWareHouse(row) {
			this.title = '新增';
			this.$refs.form.resetFields();
			this.formItem = {
				companyId: null,
				backupNo: '',
				backupName: '',
				manageBy: null,
			};
			this.addWareDialog = true;
		},
		addOk(name) {
			this.$refs[name].validate((valid) => {
				if (!valid) {
					return;
				} else {
					this.loading = true;
					if (this.title == '新增') {
						let applicant = window.localStorage.getItem('ziyunFactoryPortalName');
						addApi({ ...this.formItem, applicant }).then((res) => {
							this.loading = false;
							if (res.code === 200) {
								this.changeNum();
								this.$Message.success('新增成功');
								this.addWareDialog = false;
							} else {
								this.$Message.warning({
									content: res.msg,
									duration: 6,
									closable: true,
								});
							}
						});
					} else {
						updateMoldWarehousing(this.formItem).then((res) => {
							this.loading = false;
							if (res.code === 200) {
								this.changeNum();
								this.$Message.success('修改成功');
								this.addWareDialog = false;
							} else {
								this.$Message.warning({
									content: res.msg,
									duration: 6,
									closable: true,
								});
							}
						});
					}
				}
			});
		},
		//分页
		changeNum() {
			this.pageNum = 1;
			this.searchList();
		},
		changePageSize(pageSize) {
			this.pageSize = pageSize;
			this.searchList();
		},
		changePageNum(val) {
			this.pageNum = val;
			this.searchList();
		},
		//查询列表
		searchList() {
			let params = {
				pageNum: this.pageNum,
				pageSize: this.pageSize,
			};
			for (let key in this.searchParams) {
				if (this.searchParams[key]) {
					this.$set(params, key, this.searchParams[key]);
				}
			}
			searchApi(params).then((res) => {
				if (res.code === 200) {
					this.dataArr = res.data.records;
					this.total = res.data.total;
				} else {
					this.$Message.warning({
						content: res.msg,
						duration: 6,
						closable: true,
					});
				}
			});
		},
		viewMoldInfo(row) {
			this.infoDialogView = true;
			// getMoldInfo().then((res) => {
			//   if (res.code == 200) {
			//     this.infoDialogView = true;
			//   } else {
			//     this.$Message.warning({
			//       content: res.msg,
			//       duration: 6,
			//       closable: true,
			//     });
			//   }
			// });
		},
		getOrgList() {
			let params = {
				level: 0,
			};
			findOrgByToken(params).then((res) => {
				if (res.code === 200) {
					const obj = {
						label: 'name',
						value: 'code',
						children: 'children',
					};
					this.orgList = recursion.convertTree(res.data, obj);
				} else {
					this.$Message.warning({
						content: res.msg,
						duration: 6,
						closable: true,
					});
				}
			});
		},
		deleteOk() {
			this.loading = true;
			let params = { delIds: this.delIds };
			deleteApi(params).then((res) => {
				this.loading = false;
				if (res.code === 200) {
					this.changeNum();
					this.$Message.success('删除成功');
					this.allCheck = false;
					this.delFaultCodeShowF = false;
				} else {
					this.$Message.warning({
						content: res.msg,
						duration: 6,
						closable: true,
					});
				}
			});
		},
	},
};
</script>

<style scoped lang="scss">
.ivu-input-number {
	width: -webkit-fill-available;
}
</style>
